package com.lwj.aop;

import com.lwj.annotation.RequirePermission;
import com.lwj.exception.NoPermissionException;
import com.lwj.service.SpringUtil;
import com.lwj.service.configuration.PermissionService;
import com.lwj.utils.AopUtil;
import com.lwj.utils.CollectionTool;
import com.lwj.vo.configuration.UserInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
@Aspect
public class PermissionAspect {
    public PermissionAspect() {
    }

    public   static final String PERMISSION_CODE="permissionCode";
    @Autowired
    private PermissionService permissionService;

    @Pointcut("execution(* com.lwj.controller.*.*.*(..)) && !execution(* com.lwj.controller.test.HelloController.*(..)) ")
    public void auth() {
        // 切点
    }
    @Before("auth()")
    public void doAuth(JoinPoint joinPoint) throws Exception {
        RequirePermission annotation = AopUtil.annotation(joinPoint, RequirePermission.class);
        if(annotation==null){
            return;
        }
        List<String> values = CollectionTool.arrToList(annotation.value());
        String code = SpringUtil.getPermissionCode();
        if(StringUtils.hasText(code)){
            //前端传的code不是允许的code
            if(!values.contains(code)){
                throw new NoPermissionException();
            }
        }else {
            code=values.get(0);
        }
        UserInfo userInfo = SpringUtil.getUser();
        List<String> permissionCode = userInfo.getPermissionCode();
        //用户没有该权限code
        if(!permissionCode.contains(code)){
            throw new NoPermissionException();
        }
        permissionService.initPermissionCheckVo(code);
    }
    @After("auth()")
    public void after(){
        permissionService.removePermissionCheckVo();
    }
}
